/*Hm9gUKDDwtNjV7Mk8onAzk0GpE5soJ+BL+teTuSMJKpje/GZpyOfzSqN1XTrtObb*/
// 按钮点击事件处理
import ampub from 'ampub';
import fa from 'fa';
import moment from 'moment';
import { ajax, cardCache, DongbaToLocalTime, getLangCode, output, print, toast, formDownload } from 'nc-lightapp-front';
import CreateNCUploade from 'uap/common/components/CreateNCUploade';
import constant from '../../constants';
import { pageConfig } from '../const';
import { changeItem } from './index';
const { show: ncUploaderShow } = CreateNCUploade;
const { fa_components } = fa;
const { components, commonConst, utils } = ampub;
const { CommonKeys, SagaConst } = commonConst;
const { multiLangUtils, msgUtils, cardUtils } = utils;
const { getMultiLangByID } = multiLangUtils;
const { showConfirm, showMessage, MsgConst } = msgUtils;
const { setHeadAreaData } = cardUtils;
const { approveConst } = CommonKeys;
const { CardLinkToBill } = fa_components.CardLinkToBillUtil;
const { SagaStatus } = SagaConst;
const { LoginContext } = components;
const { getContext, loginContextKeys } = LoginContext;
const {
    printFilename,
    formId,
    area,
    pagecode,
    pkField,
    bill_type,
    transi_type,
    url,
    listRouter,
    dataSource
} = pageConfig;

export default function buttonClick(props, id) {
    // 按钮事件处理
    switch (id) {
        // 删除
        case 'Delete':
            delConfirm.call(this, props);
            break;
            // 编辑
        case 'Edit':
            editAction.call(this, props);
            break;
            // 提交
        case 'Commit':
            commit.call(this, 'SAVE', props);
            break;
            // 收回
        case 'UnCommit':
            commit.call(this, 'UNSAVE', props);
            break;
            // 刷新
        case 'Refresh':
            refresh.call(this, props);
            break;
            // 打印
        case 'Print':
            printTemp.call(this, props);
            break;
            // 输出
        case 'Output':
            outputTemp.call(this, props);
            break;
            // 下一步
        case 'Next':
            next.call(this, props);
            break;
            // 确认
        case 'Confirm':
            stepDone.call(this, props);
            break;
            // 上一步
        case 'Previous':
            prev.call(this, props);
            break;
            // 保存
        case 'Save':
            save.call(this, props);
            break;
            // 重新分配盘点人
        case 'ReInventoryPeople':
            allotAgain.call(this, props);
            break;
            // 重新分配
        case 'ReInventory':
            reInventory.call(this, props);
            break;
            // 取消
        case 'Cancel':
            cancel.call(this, props);
            break;
            // 增行
        case 'AddLine':
            addLine.call(this, props);
            break;
            // 附件
        case 'Attachment':
            attachment.call(this, props);
            break;
            // 批改
        case 'BatchAlter':
            batchAlterAction.call(this);
            break;
            // 全部相符
        case 'AllMatch':
            allMatch.call(this, props);
            break;
        // 导入
		case 'ImportBtn':
            
			Import.call(this, props);
			break;
		// 导出
		case 'ExportBtn':
			Export.call(this, props);
			break;
            // 联查减少
        case 'QueryReduce':
            linkReduce.call(this, props);
            break;
            // 联查盘盈
        case 'QueryProfit':
            linkProfit.call(this, props);
            break;
            // 联查差异调整
        case 'QueryAlter':
            linkAlter.call(this, props);
            break;
            // 审批详情
        case 'QueryAboutBillFlow':
            this.setState({
                showApprove: true,
                transi_type: this.childformData.head.transi_type.value
                    ? this.childformData.head.transi_type.value
                    : this.childformData.head.transi_type
            });
            break;
        default:
            break;
    }
}

// 转换东八区为当地时间
export function changeTime(time, format = 'YYYY-MM-DD') {
    if (time) {
        const newTime = DongbaToLocalTime(moment(time));
        return newTime.format(format);
    }
}


/**
 * 联查减少
 * @param {*} props
 */
export function linkReduce(props) {
    const pk_billcode = this.state.pk_reduce;
    if (!pk_billcode) {
        toast({ content: getMultiLangByID('201203004A-000063'), color: 'warning' });
    } else {
        const pk = pk_billcode.split('<:>')[0];
        CardLinkToBill.call(this, props, pk, 'HF');
    }
}
/**
 * 联查差异调整
 * @param {*} props
 */
export function linkAlter(props) {
    const pk_billcode = this.state.pk_alter;
    if (!pk_billcode) {
        toast({ content: getMultiLangByID('201203004A-000063'), color: 'warning' });
    } else {
        const pk = pk_billcode.split('<:>')[0];
        CardLinkToBill.call(this, props, pk, 'HG');
    }
}
/**
 * 联查盘盈
 * @param {*} props
 */
export function linkProfit(props) {
    const pk_billcode = this.state.pk_profit;
    if (!pk_billcode) {
        toast({ content: getMultiLangByID('201203004A-000063'), color: 'warning' });
    } else {
        const pk = pk_billcode.split('<:>')[0];
        CardLinkToBill.call(this, props, pk, 'HS');
    }
}
/**
 * 删除
 * @param {*} props
 */
export function delConfirm(props) {
    const pk = this.state.pk_inventory;
    if (!pk) {
        return;
    }
    showConfirm.call(this, props, {
        type: MsgConst.Type.Delete,
        beSureBtnClick: singleDel
    });
}

/**
 * 删除
 * @param {*} props
 * @param {*} operatorType
 * @param {*} commitType
 */
function singleDel(props) {
    const id = this.state.pk_inventory;
    let ts = '';
    if (this.state.current == 7) {
        ts = this.ts;
    } else {
        ts = this.childformData.head[0].values.ts.value;
    }
    const paramInfoMap = {};
    paramInfoMap[id] = ts;
    ajax({
        url: url.commit,
        data: {
            paramInfoMap,
            dataType: 'listData',
            OperatorType: 'DELETE',
            pageid: pagecode,
            commitType: 'commit' // 提交
        },
        success: (res) => {
            linkToList.call(this, props, undefined, 'browse');
        },
        error: (res) => {
            if (res && res.message) {
                toast({ content: res.message, color: 'danger' });
            }
        }
    });
}
// 提交 TODO
export function commit(OperatorType, props, content) {
    const paramInfoMap = {};
    const ts = this.ts;
    paramInfoMap[this.state.pk_inventory] = ts;
    const that = this;
    ajax({
        url: url.commit,
        data: {
            paramInfoMap,
            dataType: 'listData',
            OperatorType,
            pageid: pagecode,
            commitType: 'commit',
            content
        },
        success: (res) => {
            if (content) {
                this.setState({ compositedisplay: false });
            }
            if (res.data.success === approveConst.HASAPPROVEALTRAN) {
                // 指派信息
                const workflowData = res.data.approvealTranData;
                if (
                    workflowData.workflow
					&& (workflowData.workflow == approveConst.APPROVEFLOW
						|| workflowData.workflow == approveConst.WORKFLOW)
                ) {
                    this.setState({
                        compositedata: workflowData,
                        compositedisplay: true
                    });
                }
            } else {
                if (res.data.success === approveConst.ALLSUCCESS) {
                    this.childformData.head = JSON.parse(
                        JSON.stringify(res.data.cardVos[0].head.card_head.rows[0].values)
                    );
                    // 处理盘点范围多语
                    handleCheck_range.call(this, res.data.cardVos[0].head.card_head.rows[0].values.check_range, true);
                    this.childformData.head.check_range
						= res.data.cardVos[0].head.card_head.rows[0].values.check_range.value;
                    const bill_status
						= res.data.cardVos[0].head[constant.AREA.CARD.BODY_HEAD].rows[0].values.bill_status.value;
                    this.ts = res.data.cardVos[0].head[constant.AREA.CARD.BODY_HEAD].rows[0].values.ts.value;
                    that.setState({ bill_status }, () => {
                        toggleShow(that, props);
                    });
                    this.setState({
                        pk_reduce:
							res.data.cardVos[0].head[constant.AREA.CARD.BODY_HEAD].rows[0].values.pk_reduce.value,
                        pk_profit:
							res.data.cardVos[0].head[constant.AREA.CARD.BODY_HEAD].rows[0].values.pk_profit.value,
                        pk_alter:
							res.data.cardVos[0].head[constant.AREA.CARD.BODY_HEAD].rows[0].values.pk_alter.value
                    });
                    cardCache.updateCache(
                        'pk_inventory',
                        res.data.cardVos[0].head[constant.AREA.CARD.BODY_HEAD].rows[0].values.pk_inventory.value,
                        res.data.cardVos[0],
                        constant.AREA.CARD.BODY_HEAD,
                        constant.DATASOURCE
                    );
                    toast({ content: res.data.successMsg, color: 'success' });
                } else {
                    toast({ content: res.data.errorMsg, color: 'danger' });
                }
            }
        },
        error: (res) => {
            if (res && res.message) {
                toast({ content: res.message, color: 'danger' });
            }
        }
    });
}
/**
 * 刷新
 * @param {*} props
 */
export function refresh(props) {
    const pk = this.state.pk_inventory;
    loadingResultData.call(this, pk, () => {
        showMessage.call(this, props, { type: MsgConst.Type.RefreshSuccess });
    });
}
/**
 * 打印
 * @param {*} props
 */
export function printTemp(props) {
    const current = this.state.current;
    const printData = getPrintData.call(this, props, 'print');
    if (!printData) {
        showMessage.call(this, props, { type: MsgConst.Type.ChoosePrint });
        return;
    }
    if (current == 7) {
        // 打印时将html标题改为单据名称
        const title = document.getElementsByTagName('title');
        if (title && title[0]) {
            title[0].innerHTML = getMultiLangByID('201203004A-000059');
        }
        window.print(
            'pdf' // 支持两类：'html'为模板打印，'pdf'为pdf打印
        );
    } else {
        print(
            'pdf', // 支持两类：'html'为模板打印，'pdf'为pdf打印
            constant.URL.PRINT_CARD, // 后台打印服务url
            printData
        );
    }
}

/**
 * 输出
 * @param {*} props
 */
export function outputTemp(props) {
    const current = this.state.current;
    const printData = getPrintData.call(this, props, 'output');
    if (!printData) {
        showMessage.call(this, props, { type: MsgConst.Type.ChooseOutput });
        return;
    }
    // 如果是查询结果页面，需要将全部数据输出
    if (current == 7) {
        printData.oids[1] = '5';
    }
    output({
        url: url.print_card,
        data: printData
    });
}
/**
 * 获取打印数据
 * @param {*} props
 * @param {*} outputType
 */
function getPrintData(props, outputType = 'print') {
    const pk = this.state.pk_inventory;
    const print_param_obj = this.state.print_param;
    const checkResult = this.checkResult;
    if (!pk) {
        return false;
    }
    const filenameValue = getMultiLangByID(printFilename);
    const pks = [pk, checkResult, print_param_obj.type, print_param_obj.inventory_checkuser];
    const printData = {
        filename: filenameValue, // 文件名称
        nodekey: null, // 模板节点标识
        oids: pks, // 需要打印数据主键
        outputType // 输出类型
    };
    return printData;
}
/* 确定按钮 */
export function stepDone(props) {
    this.state.isLeaveOrRefresh = true;
    // 第二步未分配确定按钮（这个if中的意思是说，点击确定时，取得是页面缓存中的数据，而不是从数据库中读取）
    if (this.state.inventoryStatus === 'unAllot') {
        // 1. 获取传输的数据
        // 1.1 初始化一个数据结构，用来组装传输的数据
        const queryInfo = getQueryInfo(props);

        // 1.2 填充queryInfo.userdefObj属性
        const tempUserdefObj = {
            inventoryWay: this.state.inventoryWay,
            signature: this.signature,
            start_date: this.echartsData.start_date,
            end_date: this.echartsData.end_date
        };
        queryInfo.userdefObj = tempUserdefObj;

        // 1.3 填充queryInfo.userdefObj.assignData属性
        const assignData = getAssignInfo(props);
        // 第二步【分配盘点人】页面中的所有记录，从这里和后端代码来看，都是非使用人盘点时才会用的这个assignTable字段，没看懂是干什么的
        let assignTable = [];
        if (this.state.inventoryWay != 1) {
            if (this.tempEditTableDatas.rows && this.tempEditTableDatas.rows.length > 0) {
                assignTable = this.tempEditTableDatas.rows;
            }
        }
        assignData.model.rows = assignTable;
        queryInfo.userdefObj.assignData = JSON.stringify(assignData);

        // 1.4 填充queryInfo.userdefObj.unAllotData属性
        const unAllotData = getUnAllotInfo(props); // 创建一个数据结构用来存储分配盘点人列表页面上的记录用来传入到后端
        const cardData = this.props.cardTable.getAllData(constant.AREA.STEP.ANEWALLOT);
        const inventoryDatas = updateInventoryWebDatas.call(this, cardData);
        unAllotData.model.rows = inventoryDatas;
        queryInfo.userdefObj.unAllotData = JSON.stringify(unAllotData);

        // 2. 确认之后，显示柱状图
        ajax({
            url: url.query_assign,
            data: queryInfo,
            success: (res) => {
                if (res.success) {
                    // 防止重复显示，先制空
                    this.echartsData.linedata.data = [];
                    this.echartsData.linedata.name = [];
                    // 设置资产的数量
                    this.echartsData.total_num = res.data.body[area.card.body_area].rows.length;
                    // 设置盘点范围
                    this.echartsData.check_range = handleCheck_range.call(
                        this,
                        res.data.head[area.card.body_head].rows[0].values.check_range.value,
                        true
                    );
                    this.childformData.head = res.data.head[area.card.body_head].rows;
                    this.childformData.body = res.data.body[area.card.body_area].rows;
                    const tempRows = [];
                    res.data.body[area.card.body_area].rows.forEach((row) => {
                        // 存储没有分配盘点人的数据
                        if (row.values && row.values.inventory_checkuser && !row.values.inventory_checkuser.value) {
                            tempRows.push(row);
                        }
                    });
                    if (tempRows.length > 0) {
                        cardData.rows = tempRows;
                        this.tempCardTableDatas = cardData;
                    }

                    /* 给图标界面赋值 */
                    setEcharsData.call(this, res);
                    const current = this.state.current + 1;
                    this.setState({ current });
                    toggleShow(this, props);
                }
            },
            error: (res) => {
                if (res && res.message) {
                    toast({ content: res.message, color: 'danger' });
                }
            }
        });
        // 确认后未分配盘点人
    } else if (this.state.current != 7 && this.state.inventoryStatus === 'confirmedAllot') {
        // 分配盘点人中的数据
        let assignTable = [];
        if (this.state.inventoryWay != 1) {
            if (this.tempEditTableDatas.rows && this.tempEditTableDatas.rows.length > 0) {
                assignTable = this.tempEditTableDatas.rows;
            }
            // 使用人盘点
        } else {
            assignTable = [
                {
                    values: {
                        inventoryway: {
                            display: null,
                            scale: null,
                            value: '1'
                        }
                    }
                }
            ];
        }
        // 获取传输的数据
        const queryInfo = {};
        const unAllotData = getUnAllotInfo(props);
        const assignData = getAssignInfo(props);

        const tempUserdefObj = {
            // JSON.stringify(assignData);
            inventoryWay: `${this.state.inventoryWay}`,
            signature: this.signature,
            pk_inventory: this.state.pk_inventory
        };
        queryInfo.userdefObj = tempUserdefObj;
        assignData.model.rows = assignTable;
        queryInfo.userdefObj.assignData = JSON.stringify(assignData);

        const cardData = this.props.cardTable.getAllData(constant.AREA.STEP.ANEWALLOT);
        const inventoryDatas = updateInventoryWebDatas.call(this, cardData);
        unAllotData.model.rows = inventoryDatas;
        queryInfo.userdefObj.unAllotData = JSON.stringify(unAllotData);
        ajax({
            url: url.query_assign_saved,
            data: queryInfo,
            success: (res) => {
                if (res.success) {
                    // 设置盘点范围
                    this.echartsData.check_range = handleCheck_range.call(
                        this,
                        res.data.head[area.card.body_head].rows[0].values.check_range.value,
                        true
                    );
                    this.childformData.head = res.data.head[area.card.body_head].rows;
                    this.childformData.body = res.data.body[area.card.body_area].rows;
                    this.echartsData.start_date = res.data.head[area.card.body_head].rows[0].values.start_date.value;
                    this.echartsData.pk_org = res.data.head[area.card.body_head].rows[0].values.pk_org.value;
                    this.echartsData.end_date = res.data.head[area.card.body_head].rows[0].values.end_date.value;
                    /* 设置图表数据 */
                    setEcharsData.call(this, res);
                    const current = this.state.current + 1;
                    this.setState({ current });
                    toggleShow(this, props);
                }
            },
            error: (res) => {
                if (res && res.message) {
                    toast({ content: res.message, color: 'danger' });
                }
            }
        });
        // 盘点结果未分配盘点人
    } else if (this.state.current === 7) {
        const tempurl = url.skip_update;
        const updateInfo = getSaveInfo(props);
        updateInfo.head.model.rows = this.childformData.head;
        updateInfo.bodys.bodyvos.rows = this.props.cardTable.getChangedRows(constant.AREA.STEP.ANEWALLOT);
        ajax({
            url: tempurl,
            data: updateInfo,
            success: (res) => {
                this.childformData.head = res.data.head[constant.AREA.CARD.BODY_HEAD].rows;
                this.setState({ current: 7, inventoryStatus: 'confirmed' }, () => {
                    toggleShow(this, props);
                    loadingResultData.call(this, this.state.pk_inventory);
                });
            },
            error: (res) => {
                if (res && res.message) {
                    toast({ content: res.message, color: 'danger' });
                }
            }
        });
    }
}
/* 步骤条下一步按钮 */
export function next() {
    switch (this.state.current) {
        // 第一步选择
        case 0:
            StepOneExcuteNext.call(this);
            break;
            // 第二步选择
        case 1:
            StepTwoExcuteNext.call(this);
            break;
        case 2:
            if (this.state.inventoryStatus) {
                const current = this.state.current + 1;
                this.setState({ current });
            }
            break;
        default:
            break;
    }
}

function StepTwoExcuteNext() {
    // 必输项校验
    if (this.state.inventoryWay != 1) {
        // 过滤表格空行
        this.props.editTable.filterEmptyRows(constant.AREA.STEP.ALLOT_CHECKUSER, constant.ALLOT_FILED, 'include');
    }
    const inventoryStatus = this.state.inventoryStatus;
    if (inventoryStatus == 'default' || inventoryStatus == 'noAllot' || inventoryStatus == 'unAllot') {
        // 未保存时下一步点击事件
        stepTwoUnSaveExcuteNext.call(this);
    } else {
        // 已保存时下一步点击事件
        stepTwoSavedExcuteNext.call(this);
    }
}

function stepTwoSavedExcuteNext() {
    // 有可能是从列表态到重新分配盘点人，那么第二步需要将参数改为false
    this.isFromList = 'false';
    // 分配盘点人中的数据
    let assignTable = [];
    if (this.state.inventoryWay != 1) {
        this.props.editTable.filterEmptyRows(constant.AREA.STEP.ALLOT_CHECKUSER);
        // 切换页面会导致editTable的数据清空，在这里缓存
        this.tempEditTableDatas = this.props.editTable.getAllData(constant.AREA.STEP.ALLOT_CHECKUSER);
        if (this.tempEditTableDatas.rows && this.tempEditTableDatas.rows.length > 0) {
            assignTable = this.tempEditTableDatas.rows;
        }
    }
    const tempUrl = url.query_assign_saved;
    // 获取传输的数据
    const queryInfo = {};
    const assignData = getAssignInfo(this.props);
    const tempUserdefObj = {
        // JSON.stringify(assignData);
        pk_inventory: this.state.pk_inventory,
        inventoryWay: `${this.state.inventoryWay}`,
        signature: '0'
    };
    queryInfo.userdefObj = tempUserdefObj;
    assignData.model.rows = assignTable;
    queryInfo.userdefObj.assignData = JSON.stringify(assignData);
    ajax({
        url: tempUrl,
        data: queryInfo,
        success: (res) => {
            if (res.data.body[constant.AREA.CARD.BODY_AREA].rows[0].values.inventory_checkuser.value) {
                // 设置资产的数量
                this.echartsData.total_num = res.data.body[area.card.body_area].rows.length;
                // 设置盘点范围
                this.echartsData.check_range = handleCheck_range.call(
                    this,
                    res.data.head[area.card.body_head].rows[0].values.check_range.value,
                    true
                );
                this.echartsData.start_date = res.data.head[area.card.body_head].rows[0].values.start_date.value;
                this.echartsData.end_date = res.data.head[area.card.body_head].rows[0].values.end_date.value;
                this.childformData.head = res.data.head[area.card.body_head].rows;
                this.childformData.body = res.data.body[area.card.body_area].rows;
                // 设置单据号
                this.bill_code = res.data.head[area.card.body_head].rows[0].values.bill_code.value;
                /* 设置图表数据 */
                setEcharsData.call(this, res);
                this.setState({ current: 2, inventoryStatus: 'confirmed' });
                toggleShow(this, this.props);
            } else {
                // 如果有未分配盘点人跳转到分配盘点人页面
                this.signature = '1';
                let inventoryStatus = '';
                if (this.state.inventoryStatus === 'confirmed') {
                    inventoryStatus = 'confirmedAllot';
                } else {
                    inventoryStatus = 'unAllot';
                }
                this.setState({ current: this.state.current, inventoryStatus }, () => {
                    this.props.cardTable.setTableData(
                        constant.AREA.STEP.ANEWALLOT,
                        res.data.body[constant.AREA.CARD.BODY_AREA]
                    );
                });
                this.props.cardTable.setStatus(constant.AREA.STEP.ANEWALLOT, 'edit');
                const that = this;
                toggleShow(that, this.props);
            }
        },
        error: (res) => {
            if (res && res.message) {
                toast({ content: res.message, color: 'danger' });
            }
        }
    });
}

function stepTwoUnSaveExcuteNext() {
    // 分配盘点人中的数据
    let assignTable = [];
    if (this.state.inventoryWay != 1) {
        // 过滤空行
        this.props.editTable.filterEmptyRows(constant.AREA.STEP.ALLOT_CHECKUSER);
        // 切换页面会导致editTable的数据清空，在这里缓存
        this.tempEditTableDatas = this.props.editTable.getAllData(constant.AREA.STEP.ALLOT_CHECKUSER);
        if (this.tempEditTableDatas.rows && this.tempEditTableDatas.rows.length > 0) {
            assignTable = this.tempEditTableDatas.rows;
        }
    }
    const tempUrl = url.query_assign;
    // 获取传输的数据
    const queryInfo = getQueryInfo(this.props);
    const assignData = getAssignInfo(this.props);
    const tempUserdefObj = {
        // JSON.stringify(assignData);
        inventoryWay: this.state.inventoryWay,
        signature: '0',
        start_date: this.echartsData.start_date,
        end_date: this.echartsData.end_date,
        pk_inventory: this.state.pk_inventory
    };
    queryInfo.userdefObj = tempUserdefObj;
    assignData.model.rows = assignTable;
    queryInfo.userdefObj.assignData = JSON.stringify(assignData);
    ajax({
        url: tempUrl,
        data: queryInfo,
        success: (res) => {
            if (res.data) {
                const bodyRows = res.data.body[constant.AREA.CARD.BODY_AREA].rows;
                const unAllotRows = [];
                bodyRows.forEach((row) => {
                    if (!row.values.inventory_checkuser.value) {
                        unAllotRows.push(row);
                    }
                });
                this.tempCardTableDatas.rows = unAllotRows;

                // 没有未分配卡片直接到第三步
                if (!unAllotRows || unAllotRows.length == 0) {
                    // 设置资产的数量
                    this.echartsData.total_num = res.data.body[area.card.body_area].rows.length;
                    // 设置盘点范围
                    this.echartsData.check_range = handleCheck_range.call(
                        this,
                        res.data.head[area.card.body_head].rows[0].values.check_range.value,
                        true
                    );
                    this.childformData.head = res.data.head[area.card.body_head].rows;
                    this.childformData.body = res.data.body[area.card.body_area].rows;
                    /* 设置图表数据 */
                    setEcharsData.call(this, res);
                    this.setState({ current: 2, inventoryStatus: 'noAllot' });
                    toggleShow(this, this.props);
                } else {
                    // 如果有未分配盘点人跳转到分配盘点人页面
                    this.signature = '1';
                    let inventoryStatus = '';
                    if (this.state.inventoryStatus === 'confirmed') {
                        inventoryStatus = 'confirmedAllot';
                    } else {
                        inventoryStatus = 'unAllot';
                    }
                    this.childformData.head = res.data.head[area.card.body_head].rows;
                    this.childformData.body = res.data.body[area.card.body_area].rows;
                    this.setState({ current: this.state.current, inventoryStatus }, () => {
                        this.props.cardTable.setTableData(
                            constant.AREA.STEP.ANEWALLOT,
                            { rows: this.tempCardTableDatas.rows }
                        );
                        setTimeout(() => {
                            this.props.cardTable.setStatus(constant.AREA.STEP.ANEWALLOT, 'edit');
                            this.props.cardTable.setColEditableByKey(
                                constant.AREA.STEP.ANEWALLOT,
                                'inventory_checkuser',
                                false
                            );
                        }, 0);
                    });
                    toggleShow(this, this.props);
                }
            }
        },
        error: (res) => {
            if (res && res.message) {
                toast({ content: res.message, color: 'danger' });
            }
        }
    });
}

function StepOneExcuteNext() {
    if (this.props.search.getSearchValByField(constant.AREA.STEP.INVENTORY_RANGE, 'pk_org').value.firstvalue === '') {
        toast({ content: getMultiLangByID('201203004A-000026') /* 请选择财务组织！*/, color: 'warning' });
        return;
    } else if (this.props.form.getFormItemsValue(constant.AREA.STEP.INVENTORY_DATE, 'start_date').value === null) {
        toast({ content: getMultiLangByID('201203004A-000027') /* 请选择盘点开始日期！*/, color: 'warning' });
        return;
    }
    this.echartsData.start_date = this.props.form.getAllFormValue(
        constant.AREA.STEP.INVENTORY_DATE
    ).rows[0].values.start_date.value;
    this.echartsData.end_date = this.props.form.getAllFormValue(
        constant.AREA.STEP.INVENTORY_DATE
    ).rows[0].values.end_date.value;
    if (this.echartsData.end_date != null) {
        if (this.echartsData.end_date < this.echartsData.start_date) {
            toast({
                content: getMultiLangByID('201203004A-000028') /* 盘点结束日期不能早于盘点开始日期！*/,
                color: 'warning'
            });
            return;
        }
    }
    this.rangeAreaData = this.props.search.getAllSearchData(constant.AREA.STEP.INVENTORY_RANGE);
    this.dateAreaData = this.props.form.getAllFormValue(constant.AREA.STEP.INVENTORY_DATE);
    this.echartsData.search_range = this.props.search.getAllSearchData(constant.AREA.STEP.INVENTORY_RANGE);
    this.echartsData.pk_org = this.props.search.getAllSearchData(constant.AREA.STEP.INVENTORY_RANGE).conditions[0];
    // 获取传输的数据
    const queryInfo = getQueryInfo(this.props);
    const tempUserdefObj = {
        inventoryWay: this.state.inventoryWay,
        signature: '5',
        start_date: this.echartsData.start_date
    };
    queryInfo.userdefObj = tempUserdefObj;
    ajax({
        url: url.query_assign,
        data: queryInfo,
        success: (res) => {
            if (res.data) {
                if (res.data.total != 0) {
                    const that = this;
                    // 切换按钮状态
                    toggleShow(that, this.props);
                    this.echartsData.total_num = res.data.total;
                    const current = 1;
                    this.setState({ current });
                    this.signature = '0';
                } else {
                    toast({
                        content: getMultiLangByID('201203004A-000029') /* 盘点范围内不存在任何资产!*/,
                        color: 'warning'
                    });
                }
            }
        },
        error: (res) => {
            if (res && res.message) {
                toast({ content: res.message, color: 'danger' });
            }
        }
    });
}
/* 保存单击事件 */
export function save(props) {
    const current = this.state.current;
    if (current == 2) {
        stepTreeExcuteSave.call(this, props);
        // 穿透列表保存
    } else if (current == 6) {
        throughAreaExcuteSave.call(this, props);
    }
}

function throughAreaExcuteSave(props) {
    props.cardTable.filterEmptyRows(
        constant.AREA.STEP.DETAIL_LIST,
        ['asset_name', 'pk_category', 'card_num_after', 'check_result'],
        'include'
    );

    // 由于返回值只处理盘盈的数据，所以每次保存时都将盘盈数据发到后台，为了能有返回值
    const bodyDatas = this.props.cardTable.getAllData(constant.AREA.STEP.DETAIL_LIST);
    const bodyRows = bodyDatas.rows;
    bodyRows.forEach((item) => {
        // 先判断是否有盘盈数据
        if (item.values.check_result.value == 1) {
            if (item.status == 0) {
                item.status = 1; // 为了getChangeRows能够获取到
            }
        }
    });

    // 校验表体必输项
    const detailData = this.props.cardTable.getAllRows(constant.AREA.STEP.DETAIL_LIST);
    // 如果没有变动数据直接点保存，返回保存成功
    if (detailData.length <= 0) {
        const that = this;
        const inventoryStatus = 'confirmed';
        this.setState({ inventoryStatus }, () => {
            setTimeout(() => {
                props.cardTable.setStatus(constant.AREA.STEP.DETAIL_LIST, 'browse');
            }, 0);
            toggleShow(that, props);
        });
        return;
    }
    let errorMessage = '';
    for (let index = 0; index < detailData.length; index++) {
        // 如果是未处理不进行校验
        if (detailData[index].values.check_result.value == null || detailData[index].values.check_result.value == '') {
            continue;
        }
        // 如果是盘亏或者未盘不进行校验
        if (detailData[index].values.check_result.value == 2) {
            continue;
        }
        // 如果是盘盈数据--只校验资产名称和盘点后数量，并且盘点后数量大于等于1
        if (detailData[index].values.check_result.value == 1) {
            if (detailData[index].values.asset_name.value == null || detailData[index].values.asset_name.value == '') {
                errorMessage
                    += `${getMultiLangByID('201203004A-000054', { index: detailData[index].values.numberindex.value }) /* 第{index}行盘点后资产名称为空*/}\\n`;
            }
            if (
                detailData[index].values.card_num_after.value == null
                || detailData[index].values.card_num_after.value == ''
            ) {
                errorMessage
                    += `${getMultiLangByID('201203004A-000056', { index: detailData[index].values.numberindex.value }) /* 第{index}行盘点后数量为空*/}\\n`;
            } else {
                if (parseInt(detailData[index].values.card_num_after.value) < 1) {
                    errorMessage
                        += `${getMultiLangByID('201203004A-000057', { index: detailData[index].values.numberindex.value }) /* 第{index}行盘点后数量不能小于1*/}\\n`;
                }
            }

            continue;
        }
        // 先判断使用部门编码是否显示，显示在判断是否为空
        const meta = this.props.meta.getMeta();
        // let isShowUsedept = false;
        // let isShowMandept = false;
        let isUsingstatus = false;
        if (
            meta
            && meta[constant.AREA.STEP.DETAIL_LIST]
            && meta[constant.AREA.STEP.DETAIL_LIST].items
            && meta[constant.AREA.STEP.DETAIL_LIST].items.length > 0
        ) {
            meta[constant.AREA.STEP.DETAIL_LIST].items.forEach((item) => {
                // if (item.attrcode == 'pk_usedept_after_v' && item.visible == true) {
                //     isShowUsedept = true;
                // }
                // if (item.attrcode == 'pk_usedept_after' && item.visible == true) {
                //     isShowUsedept = true;
                // }
                // if (item.attrcode == 'pk_mandept_after_v' && item.visible == true) {
                //     isShowMandept = true;
                // }
                // if (item.attrcode == 'pk_mandept_after' && item.visible == true) {
                //     isShowMandept = true;
                // }
                if (item.attrcode == 'pk_usingstatus_after' && item.visible == true) {
                    isUsingstatus = true;
                }
            });
        }
        // if (
        //     isShowUsedept &&
        //     (detailData[index].values.pk_usedept_after_v.value == null ||
        //         detailData[index].values.pk_usedept_after_v.value == '')
        // ) {
        //     errorMessage += getMultiLangByID('201203004A-000058', { index: index + 1 }) /*第{index}行盘点后使用部门为空*/ + '\\n';
        // }

        if (
            isUsingstatus
            && (detailData[index].values.pk_usingstatus_after.value == null
                || detailData[index].values.pk_usingstatus_after.value == '')
        ) {
            errorMessage += `${getMultiLangByID('201203004A-000031', { index: index + 1 }) /* 第{index}行盘点后使用状况为空*/}\\n`;
        }

        // if (
        //     isShowMandept &&
        //     (detailData[index].values.pk_mandept_after_v.value == null ||
        //         detailData[index].values.pk_mandept_after_v.value == '')
        // ) {
        //     errorMessage += getMultiLangByID('201203004A-000032', { index: index + 1 }) /*第{index}行盘点后管理部门为空*/ + '\\n';
        // }
    }
    if (errorMessage.length != 0) {
        toast({
            content: errorMessage,
            color: 'danger',
            isNode: true,
            duration: 10
        });
        return;
    }
    // 穿透表体数据
    const tempurl = url.skip_update;
    const updateInfo = getSaveInfo(props);
    updateInfo.head.model.rows = this.childformData.head;
    // 需要将审批未通过的状态改为自由态
    if (
        updateInfo.head.model.rows[0].values.bill_status
		&& updateInfo.head.model.rows[0].values.bill_status.value
		&& updateInfo.head.model.rows[0].values.bill_status.value == '4'
    ) {
        updateInfo.head.model.rows[0].values.bill_status.value = '0';
        if (updateInfo.head.model.rows[0].status == 0) {
            updateInfo.head.model.rows[0].status = 1;
        }
    }
    updateInfo.bodys.bodyvos.rows = detailData;
    const validateData = {
        pageid: pagecode,
        model: {
            areaType: 'table',
            areacode: constant.AREA.STEP.DETAIL_LIST,
            rows: detailData
        }
    };
    this.props.validateToSave(validateData, () => {
        ajax({
            url: tempurl,
            data: updateInfo,
            success: (res) => {
                // 盘点范围多语显示处理
                handleCheck_range.call(
                    this,
                    res.data.head[constant.AREA.CARD.BODY_HEAD].rows[0].values.check_range,
                    true
                );
                this.childformData.head = res.data.head[constant.AREA.CARD.BODY_HEAD].rows;
                const inventoryStatus = 'confirmed';
                this.ts = res.data.head[constant.AREA.CARD.BODY_HEAD].rows[0].values.ts.value;
                const pk = res.data.head.card_head.rows[0].values.pk_inventory.value;
                this.props.setUrlParam({ id: pk });
                const i = 0;
                // let newRows = [];
                // //处理返回数据
                // bodyRows.map((item) => {
                // 	if (item.status == VOSTATUS.UPDATED || item.status == VOSTATUS.NEW) {
                // 		if (res.data.body && res.data.body[constant.AREA.STEP.DETAIL_LIST]) {
                // 			let resRows = res.data.body[constant.AREA.STEP.DETAIL_LIST].rows;
                // 			newRows.push(resRows[i]);
                // 		}
                // 		i++;
                // 	} else {
                // 		newRows.push(item);
                // 	}
                // });
                // bodyDatas.rows = newRows;
                const resRows = res.data.body[constant.AREA.STEP.DETAIL_LIST].rows;
                this.props.cardTable.setTableData(constant.AREA.STEP.DETAIL_LIST, { rows: resRows });
                // 更新缓存
                cardCache.updateCache('pk_inventory', pk, res.data, constant.AREA.CARD.BODY_HEAD, constant.DATASOURCE);
                const that = this;
                this.setState({ inventoryStatus }, () => {
                    setTimeout(() => {
                        props.cardTable.setStatus(constant.AREA.STEP.DETAIL_LIST, 'browse');
                    }, 0);
                    toggleShow(that, props);
                });
            },
            error: (res) => {
                if (res && res.message) {
                    toast({ content: res.message, color: 'danger' });
                }
            }
        });
    });
}

function stepTreeExcuteSave(props) {
    // 获取表头和表体信息
    const saveInfo = getSaveInfo(props);
    // 交易类型
    const transi_type = getContext(loginContextKeys.transtype);
    // 交易类型主键
    const pk_transi_type = getContext(loginContextKeys.pk_transtype);
    // 报告日期
    let businessDate = '';
    if (this.echartsData.end_date) {
        businessDate = this.echartsData.end_date;
    } else {
        businessDate = getContext(loginContextKeys.businessDate);
    }
    // 盘点方式
    // 分配盘点人中的数据
    const invent_way = this.state.inventoryWay;
    let inventoryWay = '';
    if (this.state.inventoryWay != 1) {
        // 非使用人盘点
        if (this.tempEditTableDatas.rows && this.tempEditTableDatas.rows.length > 0) {
            inventoryWay = this.tempEditTableDatas.rows;
        }
        // 先判断盘点方式是否有值，如果没有，则换成默认盘点方式
        if (inventoryWay == null || inventoryWay == '' || inventoryWay.length <= 0) {
            inventoryWay = [
                {
                    values: {
                        inventoryway: {
                            display: null,
                            scale: null,
                            value: '1'
                        }
                    }
                }
            ];
            this.state.inventoryWay = 1;
        } else {
            for (const key in inventoryWay) {
                inventoryWay[key].values.inventoryway.value = `${invent_way}`;
            }
        }
    } else {
        // 使用人盘点
        inventoryWay = [
            {
                values: {
                    inventoryway: {
                        display: null,
                        scale: null,
                        value: '1'
                    }
                }
            }
        ];
    }
    this.childformData.head[0].values.inventoryway.value = `${this.state.inventoryWay}`;
    this.childformData.head[0].values.transi_type.value = transi_type;
    this.childformData.head[0].values.business_date.value = businessDate;
    this.childformData.head[0].values.bill_type.value = constant.BILL_TYPE;
    this.childformData.head[0].values.pk_transitype.value = pk_transi_type;
    this.childformData.head[0].values.inv_type.value = this.inv_type;
    // 保存前校验下盘点范围的长度，如果超长则截取掉
    const check_range = this.childformData.head[0].values.check_range;
    // 盘点范围多语保存
    handleCheck_range.call(this, check_range);
    if (check_range.value != null && check_range.value.length > constant.CHECK_RANGE_LENGTH) {
        this.childformData.head[0].values.check_range.value
			= `${check_range.value.substring(0, constant.CHECK_RANGE_LENGTH)}...`;
    }
    saveInfo.head.model.rows = this.childformData.head;
    saveInfo.bodys.bodyvos.rows = this.childformData.body;
    saveInfo.bodys.tableArea2.rows = inventoryWay;
    let tempurl = url.save;
    if (this.state.inventoryStatus === 'confirmedAllot' || this.state.inventoryStatus === 'confirmed') {
        tempurl = url.update;
    }
    ajax({
        url: tempurl,
        data: JSON.stringify(saveInfo),
        success: (res) => {
            this.childformData.head = res.data.head.card_head.rows;
            // this.childformData.body = res.data.body.bodyvos.rows;
            this.bill_code = res.data.head.card_head.rows[0].values.bill_code.value;
            // 盘点范围多语显示处理
            handleCheck_range.call(this, res.data.head.card_head.rows[0].values.check_range, true);
            this.echartsData.check_range = res.data.head.card_head.rows[0].values.check_range.value;
            const pk = res.data.head.card_head.rows[0].values.pk_inventory.value;
            this.props.setUrlParam({ id: pk });
            // 保存成功后处理缓存
            if (this.state.inventoryStatus === 'confirmedAllot' || this.state.inventoryStatus === 'confirmed') {
                cardCache.updateCache('pk_inventory', pk, res.data, constant.AREA.CARD.BODY_HEAD, constant.DATASOURCE);
            } else {
                cardCache.addCache(pk, res.data, constant.AREA.CARD.BODY_HEAD, constant.DATASOURCE);
            }
            loadingResultData.call(this, pk);
            const showdata = { status: 'browse', bill_code: this.bill_code };
            setHeadAreaData.call(this, this.props, showdata);
            // setTitleData.call(this, { status: 'browse', bill_code: this.bill_code });
            this.setState({ pk_inventory: pk }, () => {
                toggleShow(this, props);
            });
        },
        error: (res) => {
            if (res && res.message) {
                toast({ content: res.message, color: 'danger' });
            }
        }
    });
}

/* 步骤条“重新分配盘点人” 按钮 */
function allotAgain(props) {
    const current = 1;
    const inventoryStatus = 'confirmed';
    const queryInfo = {};
    const tempUserdefObj = {
        pk_inventory: this.state.pk_inventory,
        signature: '7',
        inventoryWay: 1
    };
    // 把盘点的柱状图数据清空
    this.echartsData.linedata.data = [];
    this.echartsData.linedata.name = [];
    queryInfo.userdefObj = tempUserdefObj;
    ajax({
        url: url.query_assign_saved,
        data: queryInfo,
        success: (res) => {
            if (res.data) {
                if (res.data.total == 'null') {
                    toast({
                        content: getMultiLangByID('201203004A-000034') /* 所有资产已盘点完毕，不支持重新分配！*/,
                        color: 'warning'
                    });
                } else {
                    this.setState({ current, inventoryStatus }, () => {
                        props.editTable.setStatus(constant.AREA.STEP.ALLOT_CHECKUSER, 'edit');
                        const that = this;
                        toggleShow(that, props);
                    });
                }
            }
        },
        error: (res) => {
            if (res && res.message) {
                toast({ content: res.message, color: 'danger' });
            }
        }
    });
}
/* 步骤条中   “重新分配” 按钮 */
function reInventory(props) {
    let inventoryStatus = this.state.inventoryStatus;
    if (inventoryStatus == 'confirmedAllot') {
        inventoryStatus = 'confirmed';
    }
    if (inventoryStatus == 'unAllot') {
        inventoryStatus = 'default';
    }
    this.setState({ current: 1, inventoryStatus });
    props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_HALF_BTNS, false);
    props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_BTNS, true);
}
/* 步骤条中   “上一步” 按钮 */
function prev(props) {
    const inventoryStatus = this.state.inventoryStatus;
    if (inventoryStatus == 'confirmed' || inventoryStatus == 'confirmedAllot') {
        toast({
            content: getMultiLangByID('201203004A-000035') /* 允许重新分配盘点人，但不允许修改盘点范围！*/,
            color: 'warning'
        });
    } else {
        this.setState({ current: 0 });
        props.form.setAllFormValue({ childform2: this.dateAreaData });
        props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_BTNS, false);
        props.button.setButtonVisible(constant.STEP_BTNS.STEP_ONE_BTNS, true);
    }
}
/* 默认加载盘点结果数据 */
export function loadingResultData(pk, callBack) {
    const queryInfo = { pk };
    ajax({
        url: url.query_inventory_result,
        data: queryInfo,
        success: (res) => {
            // 插入前先置空数据
            this.echartsData.bar_data.x_axis = [];
            this.echartsData.bar_data.unfinished = [];
            this.echartsData.bar_data.finished = [];
            const arr = [];
            const result_category = [
                getMultiLangByID('201203004A-000004') /* 未盘*/,
                getMultiLangByID('201203004A-000036') /* 相符*/,
                getMultiLangByID('201203004A-000037') /* 不符*/,
                getMultiLangByID('201203004A-000038') /* 盘盈*/,
                getMultiLangByID('201203004A-000039') /* 盘亏*/,
                getMultiLangByID('201203004A-000040') /* 全部*/,
                getMultiLangByID('201203004A-000051') /* 不符+盘盈+盘亏*/
            ];
            for (const key in res.data) {
                const stage = [];
                const pie_values = [];
                // var obj = eval('(' + key + ')');
                const obj = JSON.parse(key);
                // 获取表头数据
                this.childformData.head = obj;
                const temp_arr = obj.def1.split('-');
                for (const temp of temp_arr) {
                    arr.push(Number(temp));
                }
                arr.push(arr[0] + arr[1] + arr[2] + arr[3] + arr[4]);
                arr.push(arr[2] + arr[3] + arr[4]);
                for (let index = 0; index < result_category.length; index++) {
                    pie_values.push({ value: arr[index] });
                }
                pie_values[5].value = arr[7];
                pie_values[6].value = arr[8];
                // 饼图数据
                this.echartsData.total_num = arr[7];
                this.echartsData.pie_data.category_total = stage;
                this.echartsData.pie_data.values = pie_values;
                // 柱状图数据
                const result_arr = res.data[key];
                if (result_arr.length != 0) {
                    for (let j = 0, len = result_arr.length; j < len; j++) {
                        this.echartsData.bar_data.x_axis.push({ value: result_arr[j].userName, id: result_arr[j].userId }),
                        this.echartsData.bar_data.unfinished.push({ value: result_arr[j].unfinished, id: result_arr[j].userId });
                        this.echartsData.bar_data.finished.push({ value: result_arr[j].finished, id: result_arr[j].userId });
                    }
                }
                // 如果有未分配人员，把未分配人员放到第一个
                if (arr[5] != 0 || arr[6] != 0) {
                    const unAllotName = getMultiLangByID('201203004A-000006');
                    this.echartsData.bar_data.x_axis.unshift({ value: unAllotName, id: unAllotName });
                    this.echartsData.bar_data.unfinished.unshift({ value: arr[6], id: unAllotName });
                    this.echartsData.bar_data.finished.unshift({ value: arr[5], id: unAllotName });
                }
                // 时间戳赋值
                this.ts = obj.ts;

                // 设置 saga 按钮状态
                const saga_status = obj.saga_status;
                const isError = SagaStatus.errorValue === saga_status;
                this.setState({
                    pk_reduce: obj.pk_reduce,
                    pk_profit: obj.pk_profit,
                    pk_alter: obj.pk_alter,
                    billInfo: {
                        isError,
                        gtxid: obj.saga_gtxid,
                        billpk: obj[pkField],
                        billtype: constant.BILL_TYPE
                    }
                });
                if (isError) {
                    // 满足条件弹出错误提示框
                    this.props.socket
						&& this.props.socket.showToast
						&& this.props.socket.showToast({
						    gtxid: obj.saga_gtxid,
						    billpk: obj[pkField]
						});
                }
            }
            // 处理盘点范围多语
            this.childformData.head.check_range = handleCheck_range.call(
                this,
                this.childformData.head.check_range,
                true
            );

            const bill_code = this.childformData.head.bill_code;
            const bill_status = this.childformData.head.bill_status;
            this.bill_code = bill_code;
            this.setState(
                {
                    current: 7,
                    inventoryStatus: 'confirmed',
                    pk_inventory: pk,
                    // bill_code: bill_code,
                    bill_status
                },
                () => {
                    toggleShow(this, this.props);
                }
            );
            const showdata = { status: 'browse', bill_code: this.bill_code };
            setHeadAreaData.call(this, this.props, showdata);
            // setTitleData.call(this, { status: 'browse', bill_code: bill_code });
            callBack && typeof callBack === 'function' && callBack.call(this);
        },
        error: (res) => {
            if (res && res.message) {
                toast({ content: res.message, color: 'danger' });
                clearUI.call(this, this.props, true);
            }
        }
    });
}

function clearUI(props) {
    this.bill_code = '';
    this.childformData = {
        head: [],
        body: [],
        way: []
    };
    this.echartsData = {
        total_num: 0,
        start_date: 0,
        end_date: 0,
        pk_org: '',
        pk_category: '',
        /* 盘点范围 */
        check_range: '',
        /* 查询区范围 */
        search_range: {},
        /**
		 * 饼图数据
		 */
        pie_data: {
            category_total: [],
            values: []
        },
        /**
		 * 盘点结果柱状图数据
		 */
        bar_data: {
            x_axis: [],
            unfinished: [],
            finished: []
        },
        /**
		 * 确定后柱状图数据
		 */
        linedata: {
            data: [],
            name: []
        }
    };
    cardCache.deleteCacheById(pkField, this.state.pk_inventory, dataSource);
    this.setState({ bill_status: '', pk_inventory: '', inventoryStatus: 'default' }, () => {
        toggleShow(this, this.props, true);
    });
}
/* 穿透列表点击事件 */
export function skipClick(index, that1) {
    const pk_inventory = that1.state.pk_inventory;
    const result_category = index;
    const current = 6;
    let inventoryStatus = 'confirmed';
    if (that1.state.bill_status != '0' && that1.state.bill_status != '4') {
        inventoryStatus = 'browse';
    }
    const { cardTable } = that1.props;
    that1.checkResult = index;
    const queryInfo = {};
    const tempUserdefObj = {
        check_result: result_category == null ? 0 : result_category,
        pk_inventory
    };
    const print_param = {
        type: 0, // 打印类型：0.按照盘点结果进行筛选的打印（默认）、1.按照盘点人对盘点明细筛选的打印、2.未分配盘点人列表的打印
        inventory_checkuser: '', // 计划盘点人的Pk值，默认为空
        check_result: tempUserdefObj.check_result, // 盘点结果的值：0.相符、1.盘盈、2.盘亏、3.不符，默认为0
    };
    queryInfo.userdefObj = tempUserdefObj;
    ajax({
        url: url.query_check_result,
        data: queryInfo,
        success: (res) => {
            if (res.data.head != null) {
                that1.echartsData.pk_org = res.data.head[constant.AREA.CARD.BODY_HEAD].rows[0].values.pk_org.value;
                that1.childformData.head = res.data.head[constant.AREA.CARD.BODY_HEAD].rows;
            }
            if (res.data.body != null) {
                that1.setState({ current, inventoryStatus, print_param }, () => {
                    toggleShow(that1, that1.props);
                });
                setTimeout(() => {
                    cardTable.setTableData(
                        constant.AREA.STEP.DETAIL_LIST,
                        res.data.body[constant.AREA.CARD.BODY_AREA],
                        null,
                        true,
                        true
                    );
                    cardTable.setStatus(constant.AREA.STEP.DETAIL_LIST, 'browse');
                }, 0);
            } else {
                that1.setState({ current, inventoryStatus, print_param }, () => {
                    toggleShow(that1, that1.props);
                });
                setTimeout(() => {
                    cardTable.setTableData(constant.AREA.STEP.DETAIL_LIST, { rows: [] });
                    cardTable.setStatus(constant.AREA.STEP.DETAIL_LIST, 'browse');
                }, 0);
            }
        },
        error: (res) => {
            if (res && res.message) {
                toast({ content: res.message, color: 'danger' });
            }
        }
    });
}
/* 获取盘点方式 */
export function queryInventoryWay(pk) {
    ajax({
        url: url.query_inventory_way,
        data: { pk },
        success: (res) => {
            if (res.data) {
                let inventoryWay = res.data.head.card_head.rows[0].values.inventoryway.value;
                // 以前在保存盘点方式时，没有考虑到非默认方式清空表体的情况，在这加个判断
                if (inventoryWay == undefined || inventoryWay == null || inventoryWay == '') {
                    inventoryWay = 1; // 默认方式
                }
                this.setState({ inventoryWay }, () => {
                    if (inventoryWay != 1 && res.data.bodys) {
                        this.props.editTable.setTableData(
                            constant.AREA.STEP.ALLOT_CHECKUSER,
                            res.data.bodys[constant.AREA.STEP.ALLOT_CHECKUSER]
                        );
                        this.isHint = false;
                    }
                });
                changeItem.call(this, inventoryWay);
            }
        },
        error: (res) => {
            if (res && res.message) {
                toast({ content: res.message, color: 'danger' });
            }
        }
    });
}
/* 修改点击事件 */
function editAction(props) {
    const pk = props.getUrlParam('id');
    ajax({
        url: url.edit,
        data: {
            pk,
            resourceCode: '2012048020'
        },
        success: (res) => {
            if (res.data) {
                toast({ color: 'danger', content: res.data });
            } else {
                this.setState({ inventoryStatus: 'edit' }, () => {
                    this.props.cardTable.setStatus(constant.AREA.STEP.DETAIL_LIST, 'edit');
                    toggleShow(this, props);
                });
            }
        }
    });
}

/**
 * 取消
 * @param {*} props
 */
export function cancel(props) {
    if (this.state.inventoryStatus == 'edit') {
        showConfirm.call(this, props, {
            type: MsgConst.Type.Cancel,
            beSureBtnClick: (props) => {
                this.setState({ current: 6, inventoryStatus: 'confirmed' }, () => {
                    toggleShow(this, props);
                    this.props.cardTable.resetTableData(constant.AREA.STEP.DETAIL_LIST);
                });
            }
        });
    } else {
        showConfirm.call(this, props, {
            color: 'warning',
            title: getMultiLangByID('msgUtils-000002') /* 国际化处理：取消 */,
            content: getMultiLangByID('201203004A-000042') /* 确定要取消当前操作信息，返回列表？*/,
            beSureBtnClick: () => {
                this.setState({ current: 0, inventoryStatus: 'default' });
                this.props.editTable.setStatus(constant.AREA.STEP.ALLOT_CHECKUSER, 'browse');
                this.state.isLeaveOrRefresh = false;
                linkToList.call(this, props, undefined, 'add');
            }
        });
    }
}
/**
 * 跳转列表
 * @param {*} props
 * @param {*} record
 */
export function linkToList(props, record = {}, status = 'browse') {
    props.pushTo(listRouter, { pagecode: pagecode.replace('card', 'list') });
}
/**
 * 返回
 * @param {*} props
 */
export function backToList(props) {
    if (this.state.current == 7) {
        if (this.state.inventoryStatus == 'confirmedAllot') {
            this.setState({ current: 7 }, () => {
                loadingResultData.call(this, this.state.pk_inventory);
            });
        } else {
            // 避免盘点结果未分配界面计划盘点人参照传值错误，确认后清空组织
            this.result_pk_org = '';
            props.pushTo(listRouter, { pagecode: pagecode.replace('card', 'list') });
        }
    } else if (this.state.current == 6) {
        this.props.cardTable.closeExpandedRow(constant.AREA.STEP.DETAIL_LIST);
        this.setState({ current: 7 }, () => {
            loadingResultData.call(this, this.state.pk_inventory);
        });
    } else {
        props.pushTo(listRouter, { pagecode: pagecode.replace('card', 'list') });
    }
}
/**
 * 新增行
 * @param {*} props
 */
export function addLine(props) {
    // let userid = getContext(loginContextKeys.userId);
    // let userName = getContext(loginContextKeys.userName);
    const numberOfRows = this.props.cardTable.getNumberOfRows(constant.AREA.STEP.DETAIL_LIST, false);
    // 增行的都是盘盈的卡片
    props.cardTable.addRow(constant.AREA.STEP.DETAIL_LIST, numberOfRows, {
        check_result: {
            display: getMultiLangByID(constant.CHECK_RESULT.PROFIT.display),
            value: constant.CHECK_RESULT.PROFIT.value
        },
        card_num_after: { display: '1', value: '1' },
        // inventory_checkuser: { display: userName, value: userid },
        // checkuser_name: { display: userName, value: userName },
        pk_inventory: {
            display: this.childformData.head.pk_inventory,
            value: this.childformData.head.pk_inventory
        }
    });
    // 新增行类别名称可以编辑
    setTimeout(() => {
        props.cardTable.setEditableByIndex(constant.AREA.STEP.DETAIL_LIST, 0, 'asset_name', true);
        props.cardTable.setEditableByIndex(constant.AREA.STEP.DETAIL_LIST, 0, 'pk_category', true);
    }, 0);
}
/**
 * 通过单据id获取缓存单据信息，没有缓存则重新查询
 * @param {*} props
 * @param {*} pk
 */
export function loadDataByPk(props, pk) {
    if (!pk || pk == 'null') {
        return;
    }
    const cachData = cardCache.getCacheById(pk, dataSource);
    if (cachData) {
        // setValue.call(this, props, cachData);
    } else {
        getDataByPk.call(this, props, pk);
    }
}
/**
 * 通过单据id查询单据信息
 * @param {*} props
 * @param {*} pk
 */
export function getDataByPk(props, pk) {
    ajax({
        url: url.queryCardUrl,
        data: {
            pagecode,
            pk
        },
        success: (res) => {
            const { success, data } = res;
            if (success) {
                if (data) {
                    // setValue.call(this, props, data);
                    cardCache.updateCache(pkField, pk, data, formId, dataSource);
                } else {
                    // setValue.call(this, props, undefined);
                    cardCache.deleteCacheById(pkField, pk, dataSource);
                    showMessage.call(this, props, { type: MsgConst.Type.DataDeleted });
                }
            }
        },
        error: (res) => {
            if (res && res.message) {
                toast({ content: res.message, color: 'danger' });
            }
        }
    });
}
/* 获取前后台传输对象 */
// 查询条件
function getQueryInfo(props) {
    const queryInfo = props.search.getQueryInfo(constant.AREA.STEP.INVENTORY_RANGE);
    // 分页信息
    const pageInfo = {
        pageIndex: 0,
        pageSize: 10,
        total: 0,
        totalPage: 0
    };
    queryInfo.pageInfo = pageInfo;
    queryInfo.pagecode = pagecode;
    queryInfo.billtype = bill_type;
    queryInfo.transtype = transi_type;

    return queryInfo;
}

/* 更新盘点数据, 盘点时需要分配盘点人的所有数据（包括页面上手动已分配和未分配的数据， 不包含数据库查询时自带盘点人的那部分数据，也就是只要能显示在未分配盘点人列表中的数据都包含在这里） */
function updateInventoryWebDatas(currentCardTableData) {
    // 使用currentCardTableData更新this.childformData.body中的数据
    // 如果this.childformData.body为空，则表示第一次点击"确定", 直接取【分配盘点人】页面上数据即可
    if (this.childformData.body.length > 0) {
        const tempAry = [];
        // 以pk_card为每一行记录的唯一标识
        currentCardTableData.rows.forEach((row) => {
            tempAry[row.values.pk_card.value] = row;
        });

        this.childformData.body.forEach((row, index) => {
            // 将【分配盘点人】页面上记录，更新到this.childformData.body中
            if (tempAry[row.values.pk_card.value]) {
                this.childformData.body[index] = tempAry[row.values.pk_card.value];
            }
        });
    } else {
        this.childformData.body = currentCardTableData.rows;
    }

    return this.childformData.body;
}

/* 未分配盘点人页面数据 */
function getUnAllotInfo(props) {
    const unAllotData = {
        pageid: '201203004A_card',
        model: {
            areaType: 'table',
            areacode: constant.AREA.STEP.ANEWALLOT,
            rows: []
        }
    };
    return unAllotData;
}
/* 未分配盘点人页面数据 */
function getAssignInfo(props) {
    const assignData = {
        pageid: '201203004A_card',
        model: {
            areaType: 'table',
            areacode: constant.AREA.STEP.ALLOT_CHECKUSER,
            rows: []
        }
    };
    return assignData;
}
/* 要保存的数据 */
function getSaveInfo(props) {
    const doneData = {
        head: {
            model: {
                areaType: 'form',
                areacode: 'card_head',
                pageInfo: {
                    pageIndex: '',
                    pageSize: '',
                    total: '',
                    totalPage: ''
                },
                rows: []
            },
            pageid: '201203004A_card'
        },
        bodys: {
            bodyvos: {
                areaType: 'table',
                areacode: 'bodyvos',
                pageInfo: {
                    pageIndex: '',
                    pageSize: '',
                    total: '',
                    totalPage: ''
                },
                rows: []
            },
            tableArea2: {
                areaType: 'table',
                areacode: 'tableArea2',
                rows: []
            }
        },

        pageid: '201203004A_card'
    };
    return doneData;
}
/**
 * 附件管理
 * @param {*} props
 */
function attachment(props) {
    // billId 是单据主键
    const billId = this.state.pk_inventory;
    ncUploaderShow.call(this, `${pagecode}-uploader`, { billId: `fa/inventory/${billId}` });
}
/**
 * 批改
 * @param {*} props
 */
export function batchAlterAction() {
    // 获取当前行的计划盘点人
    const checkUser = this.props.cardTable.getClickRowIndex(constant.AREA.STEP.ANEWALLOT).record.values.inventory_checkuser;

    // 如果当前行盘点人不为空，则可以批改
    if (!checkUser) {
        return;
    }

    // 批改结果
    const data = [];
    // 获取当前页面所有行数据
    const allDatas = this.props.cardTable.getAllData(constant.AREA.STEP.ANEWALLOT).rows;
    // 循环赋值
    allDatas.forEach((item, index) => {
        data.push({
            index,
            data: { values: { inventory_checkuser: { value: checkUser.value, display: checkUser.display } } }
        });
    });
    // 批改
    this.props.cardTable.updateDataByIndexs(constant.AREA.STEP.ANEWALLOT, data);
}
/* 把对象里的属性排序 */
function sortFun(obj, str = getMultiLangByID('201203004A-000006') /* 未分配人员*/) {
    const newObj = {}; // 排好序的新的对象
    const keys = Object.keys(obj); // 获取obj对象的属性集合，是个数组
    if (keys.join('').indexOf(str) > -1) {
        // 排除掉‘未分配人员’
        newObj[str] = obj[str];
        delete obj[str];
    }
    const values = Object.values(obj); // 获取obj对象的属性值集合，是个数组
    values.sort((a, b) => b - a); // 对数组进行降序排序
    for (let i = 0; i < values.length; i++) {
        // 按照属性值对对象进行排序
        for (const key in obj) {
            if (values[i] == obj[key]) {
                newObj[key] = values[i];
            }
        }
    }
    return newObj;
}
/**
 * 给盘点确认以及确认后图表赋值
 */
function setEcharsData(res) {
    const linedataSource = res.data.body[area.card.body_area].rows;
    const arr = {};
    const pk_name = {};
    const first = getMultiLangByID('201203004A-000006'); /* 未分配人员*/
    pk_name[first] = getMultiLangByID('201203004A-000006');
    linedataSource.forEach((value) => {
        // 把主键和当前人员盘点的数量都放到对象中
        if (value.values.inventory_checkuser.value) {
            const pks = value.values.inventory_checkuser.value;
            const pkAry = pks.split(',');
            const names = value.values.inventory_checkuser.display;
            const nameAry = names.split(',');

            pkAry.forEach((pk, index) => {
                if (!arr[pk]) {
                    arr[pk] = 1;
                    pk_name[pk] = nameAry[index];
                } else {
                    arr[pk]++;
                }
            });
        } else {
            const unallot_name = getMultiLangByID('201203004A-000006'); /* 未分配人员*/
            if (!arr[unallot_name]) {
                arr[unallot_name] = 1;
            } else {
                arr[unallot_name]++;
            }
        }
    });
    // 插入前先置空数据
    this.echartsData.linedata.name = [];
    this.echartsData.linedata.data = [];
    // 数据排序
    const sort_data = sortFun(arr);
    for (const key in sort_data) {
        if (key == getMultiLangByID('201203004A-000006') /* 未分配人员*/) {
            // ignore
        }
        this.echartsData.linedata.name.push({ value: pk_name[key], id: key });
        this.echartsData.linedata.data.push({ value: sort_data[key], id: key });
    }
}

/* 全部相符 */
function allMatch(props) {
    const result = this.props.cardTable.getVisibleRows(constant.AREA.STEP.DETAIL_LIST);
    if (result == null) {
        return;
    }

    let multiUsedeptInventory = true; // 2207版之后支持多使用盘点,  如果不存在pk_usedept_before/_v的值，那么只处理usedept_after字段即可
    const pk_usedept_before = result[0].values.pk_usedept_before.value;
    const pk_usedept_before_v = result[0].values.pk_usedept_before_v.value;
    // 如果存在但是用部门的盘点（即pk_usedept_before/_v）两个字段有值，那么只处理pk_usedept_after/_v字段的值(处理2207之前的遗留盘点单， 2207之前卡片使用部门时必填的)
    if ((pk_usedept_before && pk_usedept_before != '') || (pk_usedept_before_v && pk_usedept_before_v != '')) {
        multiUsedeptInventory = false;
    }

    // 先收集所有的pk_card，调用后台查询使用部门信息
    const pk_cards = [];
    for (let index = 0; index < result.length; index++) {
        if (result[index].values.check_result.value == 1) {
            continue;
        }
        pk_cards.push(result[index].values.pk_card.value);
    }

    if (pk_cards.length > 0) {
        const data = { allpks: pk_cards };
        ajax({
            url: url.query_cardmessage,
            data,
            success: (res) => {
                const { success, data } = res;
                if (success) {
                    if (data) {
                        const visibleRows = result;
                        const vs = JSON.parse(JSON.stringify(visibleRows));
                        const newDataSet = [];
                        vs.forEach((item, index) => {
                            // 1. 盘盈资产不处理
                            if (item.values.check_result.value == 1) {
                                return;
                            }

                            // 2. 使用部门
                            if (multiUsedeptInventory) {
                                // 2.1 2207版本：多部门使用情况下字段的赋值
                                item.values.usedept_after = {
                                    display: visibleRows[index].values.usedept_before.display,
                                    value: visibleRows[index].values.usedept_before.value
                                };
                            } else {
                                // 2.2 该代码保留（兼容2207之前的单使用部门盘点）：多部门使用情况下字段的赋值（要依赖于后台接口）
                                const deptScaleVO = data[result[index].values.pk_card.value];
                                if (deptScaleVO) {
                                    // 使用部门
                                    if (deptScaleVO.pk_dept) {
                                        // 单使用部门盘点后：显示编码
                                        item.values.pk_usedept_after = {
                                            display: visibleRows[index].values.pk_usedept_before_code.value,
                                            value: deptScaleVO.pk_dept
                                        };
                                    }

                                    // 使用部门版本
                                    if (deptScaleVO.pk_dept_v) {
                                        item.values.pk_usedept_after_v = {
                                            // 单使用部门盘点后：显示编码
                                            display: visibleRows[index].values.pk_usedept_before_code.value,
                                            value: deptScaleVO.pk_dept_v
                                        };
                                    }

                                    // pk_usedept_before在保存之前显示的是卡片多使用部门的displayname, 所以这里可以直接赋值给盘点后的name
                                    if (deptScaleVO.deptName) {
                                        item.values['pk_usedept_after.name'] = { value: deptScaleVO.deptName != '' ? deptScaleVO.deptName : visibleRows[index].values.pk_usedept_before.value };
                                        item.values['pk_usedept_after_v.name'] = { value: deptScaleVO.deptName != '' ? deptScaleVO.deptName : visibleRows[index].values.pk_usedept_before.value };
                                    }
                                }
                            }

                            // 3. 普通字符赋值
                            // 使用状况
                            item.values.pk_usingstatus_after = {
                                display: visibleRows[index].values.pk_usingstatus_before.display,
                                value: visibleRows[index].values.pk_usingstatus_before.value
                            };

                            // 管理部门版本和管理部门都需要赋值
                            item.values.pk_mandept_after_v = {
                                display: visibleRows[index].values.pk_mandept_before_v.display,
                                value: visibleRows[index].values.pk_mandept_before_v.value
                            };
                            item.values.pk_mandept_after = {
                                display: visibleRows[index].values.pk_mandept_before.display,
                                value: visibleRows[index].values.pk_mandept_before.value
                            };

                            // 使用人
                            item.values.assetuser_after = {
                                display: visibleRows[index].values.assetuser_before.display,
                                value: visibleRows[index].values.assetuser_before.value
                            };

                            // 存放地点
                            item.values.position_after = {
                                display: visibleRows[index].values.position_before.display,
                                value: visibleRows[index].values.position_before.value
                            };

                            // 货主管理组织
                            item.values.pk_ownerorg_after = {
                                display: visibleRows[index].values.pk_ownerorg_before.display,
                                value: visibleRows[index].values.pk_ownerorg_before.value
                            };
                            item.values.pk_ownerorg_after_v = {
                                display: visibleRows[index].values.pk_ownerorg_before_v.display,
                                value: visibleRows[index].values.pk_ownerorg_before_v.value
                            };
                            item.values['pk_ownerorg_after_v.name'] = {
                                value: visibleRows[index].values['pk_ownerorg_before_v.name']
                                    ? visibleRows[index].values['pk_ownerorg_before_v.name'].value
                                    : ''
                            };

                            // 使用权
                            item.values.pk_equiporg_after = {
                                display: visibleRows[index].values.pk_equiporg_before.display,
                                value: visibleRows[index].values.pk_equiporg_before.value
                            };
                            item.values.pk_equiporg_after_v = {
                                display: visibleRows[index].values.pk_equiporg_before_v.display,
                                value: visibleRows[index].values.pk_equiporg_before_v.value
                            };
                            item.values['pk_equiporg_after_v.name'] = {
                                value: visibleRows[index].values['pk_equiporg_before_v.name']
                                    ? visibleRows[index].values['pk_equiporg_before_v.name'].value
                                    : ''
                            };

                            // 盘点结果
                            item.values.check_result = {
                                display: getMultiLangByID(constant.CHECK_RESULT.EQUAL.display),
                                value: constant.CHECK_RESULT.EQUAL.value
                            };

                            // 卡片数量
                            item.values.card_num_after = {
                                display: visibleRows[index].values.card_num_before.display,
                                value: visibleRows[index].values.card_num_before.value
                            };

                            newDataSet.push({
                                index,
                                data: { values: item.values }
                            });
                        });

                        this.props.cardTable.updateDataByIndexs(constant.AREA.STEP.DETAIL_LIST, newDataSet);
                    }
                }
            }
        });
    }
}

// 为盘点单赋值
export function setOrgInventoryAttribute(
    props,
    row,
    index,
    pk_usedept_after_value,
    pk_usedept_after_v_value,
    moduleId,
    pk_usedept_after_name
) {
    // 给盘点后字段赋值
    props.cardTable.setValByKeysAndIndex(moduleId, index, {
        // 使用状况
        pk_usingstatus_after: {
            display: row.values.pk_usingstatus_before.display,
            value: row.values.pk_usingstatus_before.value
        },
        // 管理部门版本和管理部门都需要赋值
        pk_mandept_after_v: {
            display: row.values.pk_mandept_before_v.display,
            value: row.values.pk_mandept_before_v.value
        },
        pk_mandept_after: {
            display: row.values.pk_mandept_before.display,
            value: row.values.pk_mandept_before.value
        },
        // 使用人
        assetuser_after: {
            display: row.values.assetuser_before.display,
            value: row.values.assetuser_before.value
        },
        // 使用部门
        pk_usedept_after_v: {
            display: row.values.pk_usedept_before_code.value,
            value: pk_usedept_after_v_value
        },
        pk_usedept_after: {
            display: row.values.pk_usedept_before_code.value,
            value: pk_usedept_after_value
        },
        'pk_usedept_after_v.name': { value: row.values.pk_usedept_before.value },
        'pk_usedept_after.name': { value: pk_usedept_after_name != '' ? pk_usedept_after_name : row.values.pk_usedept_before.value },
        // 存放地点
        position_after: {
            display: row.values.position_before.display,
            value: row.values.position_before.value
        },
        // 货主管理组织
        pk_ownerorg_after_v: {
            display: row.values.pk_ownerorg_before_v.display,
            value: row.values.pk_ownerorg_before_v.value
        },
        pk_ownerorg_after: {
            display: row.values.pk_ownerorg_before.display,
            value: row.values.pk_ownerorg_before.value
        },
        'pk_ownerorg_after_v.name': { value: row.values['pk_ownerorg_before_v.name'] ? row.values['pk_ownerorg_before_v.name'].value : '' },
        // 使用权
        pk_equiporg_after: {
            display: row.values.pk_equiporg_before.display,
            value: row.values.pk_equiporg_before.value
        },
        pk_equiporg_after_v: {
            display: row.values.pk_equiporg_before_v.display,
            value: row.values.pk_equiporg_before_v.value
        },
        'pk_equiporg_after_v.name': { value: row.values['pk_equiporg_before_v.name'] ? row.values['pk_equiporg_before_v.name'].value : '' }
    });
}

/*
 *切换按钮状态
 */
export function toggleShow(that1, props, noData) {
    if (noData) {
        props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
    } else if (that1.state.current === 0 && that1.state.inventoryStatus === 'default') {
        props.button.setButtonVisible(constant.STEP_BTNS.STEP_ONE_BTNS, false);
        props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_BTNS, true);
    } else if (that1.state.current === 1 && that1.state.inventoryStatus === 'default') {
        props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_BTNS, false);
        props.button.setButtonVisible(constant.STEP_BTNS.STEP_THREE_BTNS, true);
    } else if (that1.state.current === 1 && that1.state.inventoryStatus === 'unAllot') {
        props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
        props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_HALF_BTNS, true);
    } else if (that1.state.current === 1 && that1.state.inventoryStatus === 'confirmed') {
        props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
        props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_BTNS, true);
    } else if (that1.state.current === 1 && that1.state.inventoryStatus === 'confirmedAllot') {
        props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
        props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_HALF_BTNS, true);
    } else if (that1.state.current === 2) {
        props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_BTNS, false);
        props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_HALF_BTNS, false);
        props.button.setButtonVisible(constant.STEP_BTNS.STEP_THREE_BTNS, true);
    } else if (that1.state.current === 3) {
        props.button.setButtonVisible(constant.STEP_BTNS.STEP_THREE_BTNS, false);
        props.button.setButtonVisible(constant.STEP_BTNS.STEP_SAVED, true);
    } else if (that1.state.current === 6 && that1.state.inventoryStatus === 'confirmed') {
        props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
        props.button.setButtonVisible(constant.STEP_BTNS.SKIP_BROWSE, true);
    } else if (that1.state.current === 6 && that1.state.inventoryStatus === 'edit') {
        props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
        props.button.setButtonVisible(constant.STEP_BTNS.SKIP_EDIT, true);
    } else if (that1.state.current === 6 && that1.state.inventoryStatus === 'browse') {
        props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
        props.button.setButtonVisible(constant.STEP_BTNS.SKIP_UNEDIT, true);
    } else if (that1.state.current === 7 && that1.state.inventoryStatus === 'confirmedAllot') {
        props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
        props.button.setButtonVisible(constant.STEP_BTNS.RESULT_UNALLOT_BUTTON, true);
    } else if (that1.state.inventoryStatus === 'confirmed' && that1.state.bill_status == '0') {
        props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
        props.button.setButtonVisible(constant.STEP_BTNS.RESULT_FREE, true);
    } else if (that1.state.inventoryStatus === 'confirmed' && that1.state.bill_status === '1') {
        props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
        props.button.setButtonVisible(constant.STEP_BTNS.RESULT_COMMIT, true);
    } else if (that1.state.inventoryStatus === 'confirmed' && that1.state.bill_status === '2') {
        props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
        props.button.setButtonVisible(constant.STEP_BTNS.RESULT_APPROVING, true);
    } else if (that1.state.inventoryStatus === 'confirmed' && that1.state.bill_status === '3') {
        props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
        props.button.setButtonVisible(constant.STEP_BTNS.RESULT_APPROVED, true);
    } else if (that1.state.inventoryStatus === 'confirmed' && that1.state.bill_status === '4') {
        props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
        props.button.setButtonVisible(constant.STEP_BTNS.RESULT_UNAPPROVED, true);
    }

    // 根据 saga 状态控制按钮状态 @ZHANGYPMTODO DEL
    // toggleSagaBtnVisible.call(that, props);
}

// 控制 saga 按钮的状态
// function toggleSagaBtnVisible(props) {
//     let isError = false;
//     if (this.childformData.head) {
//         const saga_status = this.childformData.head.saga_status;
//         isError = SagaStatus.errorValue === saga_status;
//     }
//     props.button.toggleErrorStatus(area.card.body_head, { isError });
// }

// 处理盘点范围多语，不是多语字段，也不知道为啥要处理
export function handleCheck_range(check_range, flag = false) {
    // 先判断是字符串还是对象 ----可能改变引用，可能只改变值
    if (typeof check_range === 'object') {
        if (check_range.value == null || check_range.value == '') {
            return;
        }
        check_range.value = cutOrShowCheckRange(check_range.value, flag);
    } else {
        if (typeof check_range === 'string') {
            check_range = cutOrShowCheckRange(check_range, flag);
        }
    }
    return check_range;
}

// 截断或者显示处理
function cutOrShowCheckRange(check_range_value, flag) {
    // 获取当前语种
    const language = getLangCode() || 'simpchn';
    // 看盘点范围是否以'（' 开头
    const i = check_range_value.indexOf('(');
    // 截断显示
    if (flag) {
        if (i != 0) {
            check_range_value = check_range_value.substring(i, check_range_value.length);
            // if (check_range_value.indexOf(language) != -1) {
            // 	check_range_value = check_range_value.substring(i, check_range_value.length);
            // } else {
            // 	check_range_value = null;
            // }
        }
    } else {
        // 保存处理
        if (i == 0) {
            check_range_value = language + check_range_value;
        }
    }
    return check_range_value;
}

/* 导入 */
function Import(props) {
	document.querySelector('#fileInfo').click();
	
}

export function importSuccess(retdata) {
    copyAllMatchForImport.call(this, this.props);
	let result = this.props.cardTable.getVisibleRows(constant.AREA.STEP.DETAIL_LIST);
	if (result == null) {
		return;
	}

	for (let index = 0; index < result.length; index++) {
		let id= result[index].values['asset_code'].value;//行资产编码

		let rdataRow = findDataById(id, retdata);//得到execl里的具体数据
		if(rdataRow != NaN){
			putRowValues.call(this, index, rdataRow);
		}
	}

	toast({ content: '导入成功', color: 'success' });
}

/* 导出 */
function Export(props) {
	let data = getExcelExportData(props);

	formDownload({
			params:data,
            url:'/nccloud/fa/orginventory/excelExport.do',
            enctype:2
	});
	toast({ content: '导出成功', color: 'success' });
}

function copyAllMatchForImport(props) {
    const result = this.props.cardTable.getVisibleRows(constant.AREA.STEP.DETAIL_LIST);
    if (result == null) {
        return;
    }

    let multiUsedeptInventory = true; // 2207版之后支持多使用盘点,  如果不存在pk_usedept_before/_v的值，那么只处理usedept_after字段即可
    const pk_usedept_before = result[0].values.pk_usedept_before.value;
    const pk_usedept_before_v = result[0].values.pk_usedept_before_v.value;
    // 如果存在但是用部门的盘点（即pk_usedept_before/_v）两个字段有值，那么只处理pk_usedept_after/_v字段的值(处理2207之前的遗留盘点单， 2207之前卡片使用部门时必填的)
    if ((pk_usedept_before && pk_usedept_before != '') || (pk_usedept_before_v && pk_usedept_before_v != '')) {
        multiUsedeptInventory = false;
    }

    // 先收集所有的pk_card，调用后台查询使用部门信息
    const pk_cards = [];
    for (let index = 0; index < result.length; index++) {
        if (result[index].values.check_result.value == 1) {
            continue;
        }
        pk_cards.push(result[index].values.pk_card.value);
    }

    if (pk_cards.length > 0) {
        const data = { allpks: pk_cards };
        ajax({
            url: url.query_cardmessage,
            data,
            success: (res) => {
                const { success, data } = res;
                if (success) {
                    if (data) {
                        const visibleRows = result;
                        const vs = JSON.parse(JSON.stringify(visibleRows));
                        const newDataSet = [];
                        vs.forEach((item, index) => {
                            // 1. 盘盈资产不处理
                            if (item.values.check_result.value == 1) {
                                return;
                            }

                            // 2. 使用部门
                            if (multiUsedeptInventory) {
                                // 2.1 2207版本：多部门使用情况下字段的赋值
                                item.values.usedept_after = {
                                    display: visibleRows[index].values.usedept_before.display,
                                    value: visibleRows[index].values.usedept_before.value
                                };
                            } else {
                                // 2.2 该代码保留（兼容2207之前的单使用部门盘点）：多部门使用情况下字段的赋值（要依赖于后台接口）
                                const deptScaleVO = data[result[index].values.pk_card.value];
                                if (deptScaleVO) {
                                    // 使用部门
                                    if (deptScaleVO.pk_dept) {
                                        // 单使用部门盘点后：显示编码
                                        item.values.pk_usedept_after = {
                                            display: visibleRows[index].values.pk_usedept_before_code.value,
                                            value: deptScaleVO.pk_dept
                                        };
                                    }

                                    // 使用部门版本
                                    if (deptScaleVO.pk_dept_v) {
                                        item.values.pk_usedept_after_v = {
                                            // 单使用部门盘点后：显示编码
                                            display: visibleRows[index].values.pk_usedept_before_code.value,
                                            value: deptScaleVO.pk_dept_v
                                        };
                                    }

                                    // pk_usedept_before在保存之前显示的是卡片多使用部门的displayname, 所以这里可以直接赋值给盘点后的name
                                    if (deptScaleVO.deptName) {
                                        item.values['pk_usedept_after.name'] = { value: deptScaleVO.deptName != '' ? deptScaleVO.deptName : visibleRows[index].values.pk_usedept_before.value };
                                        item.values['pk_usedept_after_v.name'] = { value: deptScaleVO.deptName != '' ? deptScaleVO.deptName : visibleRows[index].values.pk_usedept_before.value };
                                    }
                                }
                            }

                            // 3. 普通字符赋值
                            // 使用状况
                            item.values.pk_usingstatus_after = {
                                display: visibleRows[index].values.pk_usingstatus_before.display,
                                value: visibleRows[index].values.pk_usingstatus_before.value
                            };

                            // 管理部门版本和管理部门都需要赋值
                            item.values.pk_mandept_after_v = {
                                display: visibleRows[index].values.pk_mandept_before_v.display,
                                value: visibleRows[index].values.pk_mandept_before_v.value
                            };
                            item.values.pk_mandept_after = {
                                display: visibleRows[index].values.pk_mandept_before.display,
                                value: visibleRows[index].values.pk_mandept_before.value
                            };

                            // 使用人
                            item.values.assetuser_after = {
                                display: visibleRows[index].values.assetuser_before.display,
                                value: visibleRows[index].values.assetuser_before.value
                            };

                            // 存放地点
                            item.values.position_after = {
                                display: visibleRows[index].values.position_before.display,
                                value: visibleRows[index].values.position_before.value
                            };

                            // 货主管理组织
                            item.values.pk_ownerorg_after = {
                                display: visibleRows[index].values.pk_ownerorg_before.display,
                                value: visibleRows[index].values.pk_ownerorg_before.value
                            };
                            item.values.pk_ownerorg_after_v = {
                                display: visibleRows[index].values.pk_ownerorg_before_v.display,
                                value: visibleRows[index].values.pk_ownerorg_before_v.value
                            };
                            item.values['pk_ownerorg_after_v.name'] = {
                                value: visibleRows[index].values['pk_ownerorg_before_v.name']
                                    ? visibleRows[index].values['pk_ownerorg_before_v.name'].value
                                    : ''
                            };

                            // 使用权
                            item.values.pk_equiporg_after = {
                                display: visibleRows[index].values.pk_equiporg_before.display,
                                value: visibleRows[index].values.pk_equiporg_before.value
                            };
                            item.values.pk_equiporg_after_v = {
                                display: visibleRows[index].values.pk_equiporg_before_v.display,
                                value: visibleRows[index].values.pk_equiporg_before_v.value
                            };
                            item.values['pk_equiporg_after_v.name'] = {
                                value: visibleRows[index].values['pk_equiporg_before_v.name']
                                    ? visibleRows[index].values['pk_equiporg_before_v.name'].value
                                    : ''
                            };

                            newDataSet.push({
                                index,
                                data: { values: item.values }
                            });
                        });

                        this.props.cardTable.updateDataByIndexs(constant.AREA.STEP.DETAIL_LIST, newDataSet);
                    }
                }
            }
        });
    }
}

function findDataById(id, retdata){
	let result = NaN;

	for (let index = 0; index < retdata.length; index++) {
		if(id == retdata[index].asset_code.value){
			result = retdata[index];
			break;
		}
	}

	return result;
}

function putRowValues(index, rdataRow){
	let props = this.props;
    const result = this.props.cardTable.getVisibleRows(constant.AREA.STEP.DETAIL_LIST);
    // // 先收集所有的pk_card，调用后台查询使用部门信息
    // const pk_cards = [];
    // for (let index = 0; index < result.length; index++) {
    //     if (result[index].values.check_result.value == 1) {
    //         continue;
    //     }
    //     pk_cards.push(result[index].values.pk_card.value);
    // }
    // const data = { allpks: pk_cards };
    // const deptScaleVO = data[result[index].values.pk_card.value];
    
    const visibleRows = result;
    // //需要自动赋值
    props.cardTable.setValByKeysAndIndex(constant.AREA.STEP.DETAIL_LIST, index, {
		['pk_usedept_after']: {
			display: visibleRows[index].values.pk_usedept_before_code.value,
			value: visibleRows[index].values.pk_usedept_before_code.value
		}
	});
    props.cardTable.setValByKeysAndIndex(constant.AREA.STEP.DETAIL_LIST, index, {
		['pk_usedept_after_v']: {
			display: visibleRows[index].values.pk_usedept_before_code.value,
			value: visibleRows[index].values.pk_usedept_before_code.value
		}
	});
    props.cardTable.setValByKeysAndIndex(constant.AREA.STEP.DETAIL_LIST, index, {
		['pk_mandept_after']: {
			display: visibleRows[index].values.pk_mandept_before.display,
			value: visibleRows[index].values.pk_mandept_before.value
		}
	});
    props.cardTable.setValByKeysAndIndex(constant.AREA.STEP.DETAIL_LIST, index, {
		['pk_mandept_after_v']: {
			display: visibleRows[index].values.pk_mandept_before_v.display,
			value: visibleRows[index].values.pk_mandept_before_v.value
		}
	});
    // setValueByIndex.call(this, props, 'pk_usedept_after', visibleRows[index].values.pk_usedept_before_code.value, visibleRows[index].values.pk_usedept_before_code.value, index);//使用部门
    // setValueByIndex.call(this, props, 'pk_usedept_after_v', visibleRows[index].values.pk_usedept_before_code.value, visibleRows[index].values.pk_usedept_before_code.value, index);//使用部门
    // setValueByIndex.call(this, props, 'pk_usingstatus_after', visibleRows[index].values.pk_usingstatus_before.value, visibleRows[index].values.pk_usingstatus_before.display, index);//使用状况
    // setValueByIndex.call(this, props, 'pk_mandept_after_v', visibleRows[index].values.pk_mandept_before_v.value, visibleRows[index].values.pk_mandept_before_v.display, index);//管理部门版本
    // setValueByIndex.call(this, props, 'pk_mandept_after', visibleRows[index].values.pk_mandept_before.value, visibleRows[index].values.pk_mandept_before.display, index);////管理部门
    // setValueByIndex.call(this, props, 'assetuser_after', visibleRows[index].values.assetuser_before.value, visibleRows[index].values.assetuser_before.display, index);//使用人
    // setValueByIndex.call(this, props, 'position_after', visibleRows[index].values.position_before.value, visibleRows[index].values.position_before.display, index);//存放地点
    // setValueByIndex.call(this, props, 'pk_ownerorg_after', visibleRows[index].values.pk_ownerorg_before.value, visibleRows[index].values.pk_ownerorg_before.display, index);//货主管理组织
    // setValueByIndex.call(this, props, 'pk_ownerorg_after_v', visibleRows[index].values.pk_ownerorg_before_v.value, visibleRows[index].values.pk_ownerorg_before_v.display, index);//货主管理组织V
    // //货主管理组织N
    // setValueByIndex.call(this, props, 'pk_equiporg_after', visibleRows[index].values.pk_equiporg_before.value, visibleRows[index].values.pk_equiporg_before.display, index);//使用权
    // setValueByIndex.call(this, props, 'pk_equiporg_after_v', visibleRows[index].values.pk_equiporg_before_v.value, visibleRows[index].values.pk_equiporg_before_v.display, index);//使用权V
    // //使用权N

	let keys = Object.keys(rdataRow);

	for(let i = 0; i < keys.length; i++){
		let key = keys[i];

		if(isNeed(props, key)){
            //从exl获取
			let value = rdataRow[key].value;
			let display = rdataRow[key].display;
			setValueByIndex.call(this, props, key, value, display, index);
		}
	}
    // setValueByIndex.call(this, props, 'pk_usedept_after', visibleRows[index].values.pk_usedept_before_code.value, visibleRows[index].values.pk_usedept_before_code.value, index);//使用部门

	// setValueByIndex.call(this, props, 'card_num_after', '1', '1', index);
	// setValueByIndex.call(this, props, 'pk_usingstatus_after', '0001V110000000000Y5H', '运行', index);
	// setValueByIndex.call(this, props, 'pk_mandept_after', '0001V1100000000016UA', '生产类-镀铬-镀铬公共', index);

    //检查是否相符:数量相等，直接符合，不相等，就是不符合
    let card_num_after = props.cardTable.getValByKeyAndIndex(constant.AREA.STEP.DETAIL_LIST, index, 'card_num_after').value;
    let card_num_before = props.cardTable.getValByKeyAndIndex(constant.AREA.STEP.DETAIL_LIST, index, 'card_num_before').value;
    if(card_num_after == card_num_before){
        props.cardTable.setValByKeysAndIndex(constant.AREA.STEP.DETAIL_LIST, index, {
            check_result: {
                display: getMultiLangByID(constant.CHECK_RESULT.EQUAL.display),
                value: constant.CHECK_RESULT.EQUAL.value
            }
        });
    }else{
        props.cardTable.setValByKeysAndIndex(constant.AREA.STEP.DETAIL_LIST, index, {
            check_result: {
                display: getMultiLangByID(constant.CHECK_RESULT.NOT_EQUAL.display),
                value: constant.CHECK_RESULT.NOT_EQUAL.value
            }
        });
    }
}

function isNeed(props, key){

	let result = false;

	//特殊字段不处理
	if('card_num_after' == key || 'check_date' == key || 'checkuser_name' == key || 'remark' == key) {
        result = true;
	}
    
	return result;
}

function setValueByIndex(props, key, value, display, index) {
	let moduleId = constant.AREA.STEP.DETAIL_LIST;
	let oldvalue = {value : '', display: ''};

	props.cardTable.setValByKeysAndIndex(moduleId, index, {
		[key]: {
			display: display,
			value: value
		}
	});
}



function getExcelExportData(props){

	//获取需要导出的固定列
	let columns = ['card_code','pk_card','asset_name','spec','model','card_num_before','card_num_after','pk_usedept_before_code','pk_usedept_before_name','assetuser_before.code','assetuser_before','deal_result','check_date','checkuser_name','remark'];
	let colunmNames = ['卡片编码','资产编号','资产名称','规格','型号','卡片数量(盘点前)','卡片数量(盘点后)','使用部门编码(盘点前)','使用部门名称(盘点前)','使用人编码(盘点前)','使用人名称(盘点前)','处理结果','盘点日期','盘点人','备注'];
    let pk_org = '';
	//获取所有显示的值
	let datashow = [];

	let result = props.cardTable.getVisibleRows(constant.AREA.STEP.DETAIL_LIST);
	if (result == null) {
		return;
	}

    pk_org = result[0].values['pk_org'].value;

	for (let index = 0; index < result.length; index++) {
		
		let rowshow = [];

		for(let i = 0; i < columns.length; i ++){
			//卡片列
			let showvalue;

            if(result[index].values[columns[i]]){
                //字段存在
                if('pk_org' == columns[i]){
                    showvalue = result[index].values[columns[i]].value;
                }else if('card_code' == columns[i]){
                    showvalue = result[index].values[columns[i]].display
                    if(undefined == showvalue || null == showvalue || '' == showvalue){
                        showvalue = result[index].values[columns[i]].value;
                    }
                }else{
                    showvalue = result[index].values[columns[i]].display
                    if(undefined == showvalue || null == showvalue || '' == showvalue){
                        showvalue = result[index].values[columns[i]].value;
                    }
                }
    
                if(undefined == showvalue || null == showvalue || '' == showvalue){
                    showvalue = result[index].values[columns[i]].value;
                }
    
                if(showvalue == undefined) showvalue = '';

            }else{
                //字段不存在
                showvalue = '';
            }

			rowshow.push("@"+showvalue+"@");
		}
		datashow.push(rowshow);
	}

	let data = {
        pk_org : pk_org,
		columns : columns,
		colunmNames : colunmNames,
		datashow : datashow
	}
	
	return data;
}

/*Hm9gUKDDwtNjV7Mk8onAzk0GpE5soJ+BL+teTuSMJKpje/GZpyOfzSqN1XTrtObb*/